package com.xx.servlet;

import com.xx.dao.JdbcImpl;
import com.xx.dao.JdbcUtils;
import com.xx.dao.Jdbcdao;
import com.xx.pojo.User;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/updateUser")
public class UpdateServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response){
        response.setContentType("text/html;charset=UTF-8");
        System.out.println("进行更新用户");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String sex = request.getParameter("sex");
        String[] likes = request.getParameterValues("likes");
        //如果有信息没填写的话,就重新填写
        if(null==(username) || null==(password) ||null==(sex) ||null==(likes)){
            try {
                response.sendRedirect("usererror.jsp");
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        for(String s : likes){
            System.out.println(s);
        }
        ArrayList<String> list = new ArrayList<String>();
        list.add("");
        for(String s : likes){
            list.set(0,(list.get(0) + s + "#"));
        }
        String group = request.getParameter("group");
        int id = Integer.parseInt(request.getParameter("id"));
        User user = new User(id,username,password,sex,list,group);
        Jdbcdao jdbcdao = new JdbcImpl();
        int i = jdbcdao.updateUser(user);
        if(i == 1){
            try {
                response.sendRedirect("success.jsp");
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                response.sendRedirect("fail.jsp");
                return;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response){
        doGet(request,response);
    }
}
